package cn.edu.ujn.bmis.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.internet.MimeUtility;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.edu.ujn.bmis.model.SendEmail;
import cn.edu.ujn.bmis.model.UserInfo;
import cn.edu.ujn.bmis.service.SendEmailManager;
import cn.edu.ujn.bmis.service.UserInfoManager;
import cn.edu.ujn.bmis.tools.Constant;
import cn.edu.ujn.bmis.tools.Helper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Component("SendEmail")
@Scope("prototype")
public class SendEmailAction extends ActionSupport {

	private static final long serialVersionUID = 8001997562472928062L;
	private SendEmailManager sendEmailManager;
	private SendEmail sendEmail;
	private Helper helper;
	private String toEamil;
	private String theme;
	private String file;
	private String content;
	private String emailServer = "smtp.qq.com";
	private String emailEncoding = "GBK"; // Email编码
	private UserInfoManager userInfoManager;
	private List<UserInfo> userInfoList = new ArrayList<UserInfo>();
	private UserInfo userInfo;
	private String password;
	private String startTime;
	private String endTime;
	private String fromUserId;
	private String toUserId;
	private int pageNum = 1;
	private int currentPage = 1; // 当前是第几页
	private int totalCount = 0; // 总条数
	private int numPerPage = 5; // 每页显示多少条
	private int pageNumShown = 5; // 页标数字多少个
	private int pageCount = 0; // 总页数
	private String orderField;
	private String orderDirection;
	private String targetType = "navTab"; // navTab或dialog，用来标记是navTab上的分页还是dialog上的分页
	private List<SendEmail> sendEmailList = new ArrayList<SendEmail>();
	private String functionNum;
	

	@SuppressWarnings("unchecked")
	public void addSendEmail() {
		if(toEamil.contains("@qq.com")){
			emailServer="smtp.qq.com";
		}else if(toEamil.contains("@163.com")){
			emailServer="smtp.163.com";
		}else if(toEamil.contains("@126.com")){
			emailServer="smtp.126.com";
		}else if(toEamil.contains("@sina.com")){
			emailServer="smtp.sina.com";
		}
		// 当前用户
		Map session = (Map) ActionContext.getContext().getSession();
		UserInfo users = new UserInfo();
		users = (UserInfo) session.get("user");
		String arr[] = new String[30];
		EmailAttachment att1 = new EmailAttachment();
		try {
			String hql = "from UserInfo u where u.email='" + toEamil.trim()
					+ "'";
			userInfoList = userInfoManager.findUserInfo(hql);
			if (userInfoList.size() <= 0) {
				Helper.out("300", "发送的读者邮箱不存在，请检查!", "", "", "", "");
				return;
			}
			if (file != null && !"".equals(file)) {
				att1.setPath(file); // 附件原始路径
				att1.setDisposition(EmailAttachment.ATTACHMENT);
				// 是否乱码无法测试，若乱码可参考下一句解决方法
				att1.setDescription("attachemnt description gril 中文"); // 附件描述
				// 防止附件名乱码
				arr = file.split("\\\\");
				att1.setName(MimeUtility.encodeText(arr[arr.length - 1]));
			}
			MultiPartEmail email = new MultiPartEmail();
			email.setHostName(emailServer);
			email.setAuthentication(users.getEmail(), password);
			email.setCharset(emailEncoding);

			email.addTo(toEamil, toEamil); // 收信人
			email.setFrom(users.getEmail(), theme); // 发信人
			email.setSubject(theme); // 标题
			if (content == null) {
				content = " ";
			}
			email.setContent(content, "text/plain;charset=GBK");
			// email.setMsg(content); // 正文
			if (file != null && !"".equals(file)) {
				email.attach(att1); // 发送
			}
			email.send();
			// 发送时间
			Date date = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			String now = formatter.format(date);
			userInfo = userInfoList.get(0);
			SendEmail sendEmail = new SendEmail();
			sendEmail.setSendTime(now);
			sendEmail.setFromEmail(users.getEmail());
			sendEmail.setFromUserId(users.getUserId());
			sendEmail.setFromUserName(users.getUserName());
			if (file != null && !"".equals(file)) {
				sendEmail.setAttachFile(arr[arr.length - 1]);
			} else {
				sendEmail.setAttachFile(" ");
			}
			sendEmail.setTheme(theme);
			sendEmail.setToEamil(userInfo.getEmail());
			sendEmail.setToUserName(userInfo.getUserName());
			sendEmail.setToUserId(userInfo.getUserId());
			if (sendEmailManager.saveSendEmail(sendEmail)) {
				Helper.out("200", "邮件发送成功", "closeCurrent", "", "",
						"beforeSendEmail");
			} else {
				Helper.out("300", "邮件发送失败", "", "", "", "");
			}

		} catch (Exception e) {
			e.printStackTrace();
			Helper.out("300", "邮件发送失败", "", "", "", "");
		} // 附件名称
	}

	/**
	 * 查看发送邮件记录
	 */
	@SuppressWarnings("unchecked")
	public String findSendEmail() {
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql = "";
		String hql_size = "";
		try {
			Date temp=null;
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			temp=dateFormat.parse(endTime);
			Calendar cal = new GregorianCalendar();
			cal.setTime(temp);
			cal.add(Calendar.DATE,1);
			Date d = cal.getTime();
			endTime  = dateFormat.format(d);
		} catch (Exception e) {
			e.printStackTrace();
		}
		hql = "select s from SendEmail s where s.id=s.id ";
		hql_size = "select count(*) from SendEmail s where s.id=s.id ";
		if (fromUserId != null && !"".equals(fromUserId)) {
			hql += " and s.fromUserId='" + fromUserId.trim() + "' ";
			hql_size += " and s.fromUserId='" + fromUserId.trim() + "' ";
		}
		if (toUserId != null && !"".equals(toUserId)) {
			hql += " and s.toUserId='" + toUserId.trim() + "' ";
			hql_size += " and s.toUserId='" + toUserId.trim() + "' ";
		}
		if (startTime != null && !"".equals(startTime) && endTime != null
				&& !"".equals(endTime)) {
			hql += " and s.sendTime >= CONVERT(datetime, '"
					+ startTime.trim() + "') and s.sendTime < CONVERT(datetime, '"
					+ endTime.trim() + "') ";
			hql_size += " and s.sendTime >= CONVERT(datetime, '"
				+ startTime.trim() + "') and s.sendTime < CONVERT(datetime, '"
				+ endTime.trim() + "') ";
		}
//		if (startTime != null && !"".equals(startTime) && endTime != null
//				&& !"".equals(endTime)) {
//			hql += " and s.sendTime between CONVERT(datetime, '"
//					+ startTime.trim() + "',120) and CONVERT(datetime, '"
//					+ endTime.trim() + "',120) ";
//			hql_size += " and s.sendTime between CONVERT(datetime, '"
//					+ startTime.trim() + "',120) and CONVERT(datetime, '"
//					+ endTime.trim() + "',120) ";
//		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		sendEmailList = helper.fenYe(hql, this.currentPage, this.numPerPage);
		return SUCCESS;
	}

	/**
	 * 进入发送邮件页面
	 */
	public String beforeSendEmail() {
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		return SUCCESS;
	}

	public SendEmailManager getSendEmailManager() {
		return sendEmailManager;
	}

	@Resource(name = "sendEmailManager")
	public void setSendEmailManager(SendEmailManager sendEmailManager) {
		this.sendEmailManager = sendEmailManager;
	}

	public SendEmail getSendEmail() {
		return sendEmail;
	}

	public void setSendEmail(SendEmail sendEmail) {
		this.sendEmail = sendEmail;
	}

	public Helper getHelper() {
		return helper;
	}

	@Resource(name = "helper")
	public void setHelper(Helper helper) {
		this.helper = helper;
	}

	public String getToEamil() {
		return toEamil;
	}

	public void setToEamil(String toEamil) {
		this.toEamil = toEamil;
	}

	public String getTheme() {
		return theme;
	}

	public void setTheme(String theme) {
		this.theme = theme;
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public UserInfoManager getUserInfoManager() {
		return userInfoManager;
	}

	@Resource(name = "userInfoManager")
	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public List<UserInfo> getUserInfoList() {
		return userInfoList;
	}

	public void setUserInfoList(List<UserInfo> userInfoList) {
		this.userInfoList = userInfoList;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String getFromUserId() {
		return fromUserId;
	}

	public void setFromUserId(String fromUserId) {
		this.fromUserId = fromUserId;
	}

	public String getToUserId() {
		return toUserId;
	}

	public void setToUserId(String toUserId) {
		this.toUserId = toUserId;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public int getPageNumShown() {
		return pageNumShown;
	}

	public void setPageNumShown(int pageNumShown) {
		this.pageNumShown = pageNumShown;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	public String getTargetType() {
		return targetType;
	}

	public void setTargetType(String targetType) {
		this.targetType = targetType;
	}

	public List<SendEmail> getSendEmailList() {
		return sendEmailList;
	}

	public String getFunctionNum() {
		return functionNum;
	}

	public void setFunctionNum(String functionNum) {
		this.functionNum = functionNum;
	}
	
}
